const express = require("express");
const router = express.Router();
const sqlFn = require("./mysql");
const jwt = require("jsonwebtoken");
const config = require("./config");
const url = require("url");

/**
 * 登陆接口
 */
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  const sql = "select * from user where `username`=? and `password`=?";
  const arr = [username, password];
  sqlFn(sql, arr, (result) => {
    // 返回用户信息
    if (result.length > 0) {
      // console.log('登录成功');
      const token = jwt.sign(
        {
          id: result[0].id,
          username: result[0].username,
        },
        config.jwtSecret
      );
      res.send(token);
    } else {
      res.status(401).json({
        errors: "用户名密码错误",
      });
    }
  });
});

// // 登录接口
// router.post("/Registered", (req, res) => {
//   const sql = "insert into user values(null,?,?)";
//   const { username, password } = req.body;
//   const arr = [username, password];
//   sqlFn(sql, arr, (result) => {
//     if (result.affectedRows > 0) {
//       res.send({
//         msg: "成功",
//       });
//     } else {
//       res.status(401).json({
//         errors: "用户名密码错误",
//       });
//     }
//   });
// });





module.exports = router;
